//
//  PartyRefreshRequestViewController.m
//  UESTCPioneer
//
//  Created by Apple on 14-5-18.
//  Copyright (c) 2014年 Sway. All rights reserved.
//

#import "PartyRefreshRequestViewController.h"
#import "PioneerNewsEntity.h"
#import "UPTitleCell.h"
#import "UPMainInfoCell.h"
#import "UPFooterCell.h"
#import "PartyCommentViewController.h"
#import "PartyThinkingReportEntity.h"

static NSString *customTitleCellIndentifier = @"CustomTitleCellIndentifier";
static NSString *customMainCellIndentifier = @"CustomMainCellIndentifier";
static NSString *customFooterCellIndentifier = @"ThinkingReportFooterCellIndentifier";
@interface PartyRefreshRequestViewController ()<UPMainInfoCellDelegate,UPTitleCellDelegate,UPFooterCellDelegate>{
    
    NSMutableDictionary *_cellHeightDictionary;
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;

@end

@implementation PartyRefreshRequestViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

-(void)_initRequestRequireEntityName:(NSString*)EntityName
                          EntityMapping:(NSDictionary*)EntityMapping
                          RequestData:(NSDictionary*)RequestData
                          CommentListRequestData:(NSDictionary*)CommentListRequestData
                          CommentWriteRequestData:(NSDictionary*)CommentWriteRequestData
                          CommentIdKey:(NSString*)CommentIdKey
                          CommentContentKey:(NSString*)CommentContentKey
                          CommentListKeyMapping:(NSDictionary*)CommentListKeyMapping{
    
    entityName=EntityName;
    entityMapping=EntityMapping;
    requestData=RequestData;
    
    //请求评论列表用的参数
    commentListRequestData=CommentListRequestData;
    //写评论请求用的参数
    commentWriteRequestData=CommentWriteRequestData;
    
    commentIdKey=CommentIdKey;
    
    commentContentKey=CommentContentKey;
    
    commentListKeyMapping=CommentListKeyMapping;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    [self.tableView registerClass:[UPTitleCell class] forCellReuseIdentifier:customTitleCellIndentifier];
    [self.tableView registerClass:[UPMainInfoCell class] forCellReuseIdentifier:customMainCellIndentifier];
    [self.tableView registerClass:[UPFooterCell class] forCellReuseIdentifier:customFooterCellIndentifier];
    
    _cellHeightDictionary=[[NSMutableDictionary alloc]init];
    
    //@AGPhotoBrowser
    AGPhotoBrowserView *photoBrowser = [[AGPhotoBrowserView alloc]init];
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - refresh request
-(void)pullDownRefresh:(MJRefreshBaseView *)refreshView{
    [PublicMethod ClearEntity:entityName];
    
    [NetworkCenter RKRequestWithData:requestData EntityName:entityName Mapping:entityMapping SuccessBlock:^(NSArray *resultArray) {
        NSMutableArray *dic=    [[NSMutableArray alloc]init];
        [dic addObjectsFromArray:resultArray];
        NSLog(@"dic = %@",dic);
        
        tableViewEntitiesArray=[[NSArray alloc]initWithArray:dic];
        
        [self.tableView reloadData];
        PullUpRefreshTimes=0;
        /*add for  党课心得*/
        for (int i = 0; i < tableViewEntitiesArray.count; i ++) {
            NewsEntity *entity= tableViewEntitiesArray[i];
            NSInteger theid = [entity.theId integerValue];
            if (maxNotification < theid) {//获取最小的theId
                maxNotification = theid;
            }
        }
        /**/
        [refreshView endRefreshing];
    } failure:^(NSError *error) {
        NSLog(@"%@ 下拉请求失败",entityName);
        [refreshView endRefreshing];
    }];
}

-(void)pullUpRefresh:(MJRefreshBaseView *)refreshView{
    NSMutableDictionary *dic = [[NSMutableDictionary alloc]initWithDictionary:requestData];
    [dic setObject:[NSString stringWithFormat:@"%d",PullUpRefreshTimes+2] forKey:@"page"];
//    [dic setObject:@"0" forKey:@"page"];
    [dic setObject:[NSString stringWithFormat:@"%d",maxNotification] forKey:@"id"];
    
    NSLog(@"page = %@",[NSString stringWithFormat:@"%d",PullUpRefreshTimes+2]);
    NSLog(@"上拉请求“交思想汇报通知”的请求数据是\n:%@",dic);
    [NetworkCenter RKRequestWithData:dic EntityName:entityName Mapping:entityMapping SuccessBlock:^(NSArray *resultArray) {
       
        NSLog(@"pullUpRefresh resultArray = %@",resultArray);
        for (PioneerNewsEntity* entity in tableViewEntitiesArray){
            NSLog(@"%@",entity.titleBody);
        }
        
        if ([resultArray count]==0){
            [refreshView endRefreshing];
            return ;
        }
        
        NSMutableArray *newArray = [[NSMutableArray alloc]init];
        [newArray addObjectsFromArray:tableViewEntitiesArray];
        [newArray addObjectsFromArray:resultArray];
        NSArray *result = [[NSArray alloc]initWithArray:newArray];
        
        
        tableViewEntitiesArray=result;
        
        [self.tableView reloadData];
        
        //清除core data 因为现在还没有适合下拉刷新和适合本地缓存的api
        
        [refreshView endRefreshing];
        PullUpRefreshTimes++;
        
    } failure:^(NSError *error) {
        NSLog(@"%@ 上拉error:%@",entityName,error);
        [refreshView endRefreshing];
    }];
}


-(void)commentButtonPress:(commentButton*)button{
    PartyCommentViewController *comment = [[PartyCommentViewController alloc]init];
    
    
    //    1）type：writeShareComment  （2）user_id：用户的账号
    //    （3）username：用户姓名      （4）shareId：活动分享的id
    //    （5）comment：评论的内容
    
    comment.commenTag = @"ThinkingReport";
    //请求评论列表用的参数
    NSMutableDictionary *dic = [[NSMutableDictionary alloc]initWithDictionary:commentListRequestData];
    [dic setObject:[NSString stringWithFormat:@"%d",button.theId] forKey:commentIdKey];
    commentListRequestData=[[NSDictionary alloc]initWithDictionary:dic];
    //请求提交评论用的参数
    NSMutableDictionary *temp = [[NSMutableDictionary alloc]initWithDictionary:commentWriteRequestData];
    [temp setObject:[NSString stringWithFormat:@"%d",button.theId] forKey:commentWriteIdKey];
    commentWriteRequestData=[[NSDictionary alloc]initWithDictionary:temp];
    //请求评论列表用的参数
    comment.commentListRequestData=commentListRequestData;
    //写评论请求用的参数
    comment.commentRequestData=commentWriteRequestData;
    comment.commentContentKey=commentContentKey;
    comment.commentListKeyMapping=commentListKeyMapping;
    comment.numberOfComment=[button.titleLabel.text integerValue];
    
    
    [self.leveyTabBarController.navigationController pushViewController:comment animated:YES];
}

#pragma mark - 全文按钮事件

//代理函数
-(void)WholeNewsButtonClick1:(NSInteger)theId{
    
    NSLog(@"kPartyThinkingReportEntity = %@,theId = %i",kPartyThinkingReportEntity,theId);
    PartyThinkingReportEntity *entity = [PublicMethod entity:kPartyThinkingReportEntity WithId:theId];
    NSLog(@"!!!!!!!!!!!!!!!entity = %@",entity);
    NSString *content=entity.newsBody;
    UIViewController *viewController = [[UIViewController alloc]init];
    UITextView *textView = [[UITextView alloc]init];
    
    [viewController.view addSubview:textView];
    [textView setText:content];
    [textView setEditable:NO];
    [textView setScrollEnabled:YES];
    [textView setFont:[UIFont systemFontOfSize:18]];
    
    [textView setTranslatesAutoresizingMaskIntoConstraints:NO];
    [viewController.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[textView]|" options:0 metrics:Nil views:NSDictionaryOfVariableBindings(textView)]];
    [viewController.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[textView]|" options:0 metrics:Nil views:NSDictionaryOfVariableBindings(textView)]];
    
    [self.leveyTabBarController.navigationController pushViewController:viewController animated:YES];
}
-(void)WholeNewsButtonClick:(NSInteger)theId{
    PartyThinkingReportEntity *entity = [PublicMethod entity:kPartyThinkingReportEntity WithId:theId];
    
    NSString *content =entity.newsBody;
    UIViewController *viewController = [[UIViewController alloc]init];
    
    [viewController.view setFrame:self.view.frame];
    [viewController.view setBackgroundColor:[UIColor colorWithRed:232.0f/255.0f green:232.0f/255.0f blue:232.0f/255.0f alpha:1.0f]];
    
    UILabel * label = [[UILabel alloc] initWithFrame:CGRectMake(viewController.view.frame.origin.x, viewController.view.frame.origin.y, viewController.view.frame.size.width, 45)];
    
    /*
    NSString *title = entity.userName;
    label.text = title;
     */
    label.text = @"党课作业";
    [label setBackgroundColor:[UIColor colorWithRed:232.0f/255.0f green:232.0f/255.0f blue:232.0f/255.0f alpha:1.0f]];
    [label setFont:[UIFont systemFontOfSize:17]];
    //    [label setTextColor:[UIColor grayColor]];
    //文字居中显示
    label.textAlignment = NSTextAlignmentCenter;
    //自动折行设置
    //    label.lineBreakMode = NSLineBreakByWordWrapping;
    label.numberOfLines = 0;
    label.adjustsFontSizeToFitWidth = YES;

    [viewController.view addSubview:label];
    [label setTranslatesAutoresizingMaskIntoConstraints:NO];
    [viewController.view addConstraint:[NSLayoutConstraint constraintWithItem:label
                                                                    attribute:NSLayoutAttributeTop
                                                                    relatedBy:NSLayoutRelationEqual
                                                                       toItem:viewController.view
                                                                    attribute:NSLayoutAttributeTop
                                                                   multiplier:1 constant:0]];

    [viewController.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-3.0-[label]-3.0-|" options:0 metrics:Nil views:NSDictionaryOfVariableBindings(label)]];
    [viewController.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[label(==30)]" options:0 metrics:Nil views:NSDictionaryOfVariableBindings(label)]];
    UITextView *textView = [[UITextView alloc]init];
    [textView setText:content];
    [textView setEditable:NO];
    [textView setScrollEnabled:YES];
    [textView setFont:[UIFont systemFontOfSize:18]];
    [textView setBackgroundColor:[UIColor colorWithRed:232.0f/255.0f green:232.0f/255.0f blue:232.0f/255.0f alpha:1.0f]];
    [viewController.view addSubview:textView];
    [textView setTranslatesAutoresizingMaskIntoConstraints:NO];
    [viewController.view addConstraint:[NSLayoutConstraint constraintWithItem:textView
                                                                    attribute:NSLayoutAttributeTop
                                                                    relatedBy:NSLayoutRelationEqual
                                                                       toItem:label
                                                                    attribute:NSLayoutAttributeBottom
                                                                   multiplier:1
                                                                     constant:0]];
    [viewController.view addConstraint:[NSLayoutConstraint constraintWithItem:textView
                                                                    attribute:NSLayoutAttributeBottom
                                                                    relatedBy:NSLayoutRelationEqual
                                                                       toItem:viewController.view
                                                                    attribute:NSLayoutAttributeBottom
                                                                   multiplier:1
                                                                     constant:-5]];
    [viewController.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[textView]|" options:0 metrics:Nil views:NSDictionaryOfVariableBindings(textView)]];
    //    [viewController.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[textView(==300)]|" options:0 metrics:Nil views:NSDictionaryOfVariableBindings(textView)]];
    
    
    [self.leveyTabBarController.navigationController pushViewController:viewController animated:YES];
}


#pragma mark - tableView Cell dequeue
- (UITableViewCell *)tableView:(UITableView *)tableView  cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    //    NSLog(@"super tableview delegate");
    
    NewsEntity *entity= tableViewEntitiesArray[indexPath.section];
    NSInteger theid = [entity.theId integerValue];
    if (maxNotification > theid) {
        maxNotification = theid;
    }
//    NSLog(@"entity = %@",entity);
    
    if (indexPath.row == 0) {
        //6.0后用这种方式更直接，可以省掉if（cell2＝＝nil）的判断   @黄卓越 2014-3-28
        UPTitleCell *cell = [tableView dequeueReusableCellWithIdentifier:customTitleCellIndentifier forIndexPath:indexPath];
        cell.theId=[entity.theId integerValue];
        [cell setTitle:entity.titleBody];
        [cell setTime:entity.timeAndDate];
        return cell;
    }
    else if (indexPath.row == 1) {
        
        //6.0后用这种方式更直接，可以省掉if（cell2＝＝nil）的判断   @黄卓越 2014-3-28
        UPMainInfoCell *cell2 = [tableView dequeueReusableCellWithIdentifier:customMainCellIndentifier forIndexPath:indexPath];
        //@cell的高度自适应
        if ([cell2 hasImage])_cellHeightDictionary[@(indexPath.section)]=@(110+imageViewWidth);
        else _cellHeightDictionary[@(indexPath.section)]=@(110);
        [cell2 setNewsBody:entity.newsBody];
        cell2.theId=[entity.theId integerValue];
        cell2.delegate=self;
        return cell2;
    }
    else {
        //6.0后用这种方式更直接，可以省掉if（cell2＝＝nil）的判断   @黄卓越 2014-3-28
        UPFooterCell *cell3 = [tableView dequeueReusableCellWithIdentifier:customFooterCellIndentifier forIndexPath:indexPath];
        
        /*修改*/
        for (UIView * view in  cell3.contentView.subviews) {
            if (view.tag == 100) {
                [view removeFromSuperview];
            }
        }
        /**/
//        UPFooterCell *cell3 = [tableView dequeueReusableCellWithIdentifier:customFooterCellIndentifier forIndexPath:indexPath];
        cell3.theId=[entity.theId integerValue];
        cell3.delegate=self;
        UIButton *btn1 = (UIButton *)[cell3.contentView viewWithTag:btn1Tag];
        
        [cell3 setCommentId:[entity.theId integerValue]];
        [cell3 setCommentNum:[entity.numberOfComment integerValue]];
        [cell3 addCommentButtonTaget:self Action:@selector(commentButtonPress:)];
        
        /*修改*/
        if (self.fromSourceEnable) {
            [cell3 setFromSourceStatus:YES fromSource:self.source];
            //            cell3.comfromLabel.text = @"";
            //            cell3.comfromLabel.text = [NSString stringWithFormat:@"来自于: %@",self.source];
            //            [cell3.comfromLabel setFont:[UIFont systemFontOfSize:[UIFont smallSystemFontSize]]];
        }
        /**/
        
        self.cell3 = cell3;
        [btn1 setImage:[UIImage imageNamed:@"file.png"] forState:UIControlStateNormal];
        return cell3;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {
        return 55;
    }
    else if (indexPath.row == 1){
        //判断是否有图片以适应高度
        CGFloat height;
        height=110;
        return height;
    }
    else
        return 40;
}


-(void)getSiXiangList{

    [PublicMethod ClearEntity:entityName];
    NSLog(@"requestData = %@",requestData);
    NSLog(@"entityName = %@",entityName);
    [NetworkCenter RKRequestWithData:requestData EntityName:entityName Mapping:entityMapping SuccessBlock:^(NSArray *resultArray) {
        NSMutableArray *dic=    [[NSMutableArray alloc]init];
        [dic addObjectsFromArray:resultArray];
        NSLog(@"dic = %@",dic);
        
        tableViewEntitiesArray=[[NSArray alloc]initWithArray:dic];
        
        [self.tableView reloadData];
        PullUpRefreshTimes=0;
    } failure:^(NSError *error) {
        [Alert showAlert:@"下拉请求失败!"];
        return ;
    }];
    
    [self.tableView reloadData];


}

/**
 *  add for 心得
 */

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{

    PartyCommentViewController *comment = segue.destinationViewController;
    comment.delegate = self;
}
@end
